package com.mangowang.module.main.web.ui;

import android.Manifest;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.mangowang.lib.common.BuildConfig;
import com.mangowang.lib.common.R;
import com.mangowang.lib.common.base.BaseActivity;
import com.mangowang.lib.common.help.PermissionHelper;
import com.mangowang.lib.common.help.UserHelper;
import com.mangowang.lib.common.util.GsonUtils;
import com.mangowang.lib.common.util.ImageUtil;
import com.mangowang.lib.common.util.LogUtil;
import com.mangowang.lib.common.util.SaveViewToImageUtil;
import com.mangowang.lib.common.util.StatusBarUtil;
import com.mangowang.module.main.ui.MainActivity;
import com.mangowang.module.main.web.inteface.JavaScriptInterface;
import com.mangowang.module.main.web.manager.MyChromeClient;
import com.mangowang.module.main.web.manager.WebViewClientUtil;

import java.io.File;
import java.lang.ref.WeakReference;

import butterknife.ButterKnife;

public class WebViewActivity extends BaseActivity implements WebViewClientUtil.WebClientLoadListener,
        MyChromeClient.ProgressChangedListener, MyChromeClient.ReceivedTitleListener {


    //全局声明，用于记录选择图片返回的地址值
    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private static final String KEY_WEBURL = "KEY_WEBURL";
    public static final int BACK = 0x1fe;
    public static final int GOTOCARDPRINT = 0x2fe;
    public static final int GOTOCAPTURE = 0x3fe;
    public static final int LOGIN = 0x4fe;
    public static final int LOGIN_OUT = 0x5fe;
    public static final int GOTOMAIN = 0x6fe;
    public static final int TAKEPHOTO = 0x7fe;
    public static final int JUMPTO = 0x8fe;
    public static final int DOWNLOAD = 0x9fe;
    public static final int SAVE = 0x1ff;

    //文件选择所需
    public final static int FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5 = 2;
    public final static int FILE_CHOOSER_RESULT_CODE = 1;// 表单的结果回调


    WebView webView;
    ProgressBar prograssBar;
    private MyChromeClient myChromeClient;
    private String url;
    public String methodName = "";


    private Handler jsInterfaceHandler ;

    RelativeLayout rvMessage;


    /**
     * 不带参数的地址
     *
     * @param context
     * @param url
     */
    public static void startActivity(Context context, String url) {
        if (context == null) return;
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(KEY_WEBURL, url);
        context.startActivity(intent);
    }

    public static Intent startIntentActivity(Context context, String url) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(KEY_WEBURL, url);
        return intent;
    }

    /**
     * 不带参数的地址
     *
     * @param context
     * @param url
     */
    public static void startActivity(Context context, String url, boolean only) {
        if (context == null) return;
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(KEY_WEBURL, url);
        intent.putExtra("only", only);
        context.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
//        MainApplication.addWebActivity(this);
        ButterKnife.bind(this);
        StatusBarUtil.setStatusBarLightMode(this, Color.parseColor("#ffffff"), true);
        initWebView();

    }

    //同步cookie
    private void syncCookie(Context context, String url) {
        try {
            CookieSyncManager.createInstance(context);
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.removeAllCookie();
            cookieManager.setCookie(url, "key=" + UserHelper.getCurrentToken());
            String newCookie = cookieManager.getCookie(url);
            if (newCookie != null) {
                LogUtil.d("Wang", "设置Cookie url=" + url + " ;   cookie=" + newCookie);
            }
        } catch (Exception e) {
            LogUtil.e("Wang: webView.syncCookie failed", e.toString());
        }
    }


    private void initWebView() {
        rvMessage = findViewById(R.id.rv_message);
        prograssBar = findViewById(R.id.prograssBar);
        webView = findViewById(R.id.webViews);
        jsInterfaceHandler = new JsInterfaceHandler(this, webView, rvMessage);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new JavaScriptInterface(jsInterfaceHandler), "app");
        webView.setWebViewClient(new WebViewClientUtil(this, this));
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setBlockNetworkImage(false);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.getSettings().setLoadsImagesAutomatically(true);// 加载网页中的图片
        webView.getSettings().setUseWideViewPort(true); //设置使用视图的宽端口
        webView.setWebChromeClient(myChromeClient = new MyChromeClient(this, this, this, webView, null));
        webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        url = getIntent().getStringExtra(KEY_WEBURL);
        if (!url.contains("http")) {
            url = BuildConfig.BASE_URL + getIntent().getStringExtra(KEY_WEBURL);
        }
        if (getIntent().getBooleanExtra("only", false)) {
            loadUrl();
        } else {
            if (url.contains("key")) {
                webView.loadUrl(url);
            } else {
                String newUrl;
                //统一拼接可
                if (UserHelper.isLogin()) {
                    if (url.contains("?")) {
                        newUrl = url + "&key=" + UserHelper.getCurrentToken() + "&isBack=1";
                    } else {
                        newUrl = url + "?key=" + UserHelper.getCurrentToken() + "&isBack=1";
                    }
                } else {
                    newUrl = url + "&isBack=true";
                }
                LogUtil.e("wang", "网页请求地址：" + newUrl);
                webView.loadUrl(newUrl);
            }

        }

    }

    private void loadUrl() {
        webView.loadDataWithBaseURL(null, getIntent().getStringExtra(KEY_WEBURL), "text/html", "utf-8", null);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (webView != null) {
            webView.destroy();
        }
    }


    public void onResume() {

        super.onResume();
    }

    @Override

    public void onPause() {

        super.onPause();

    }


    @Override
    public void onConfigurationChanged(Configuration config) {
        super.onConfigurationChanged(config);
        switch (config.orientation) {
            case Configuration.ORIENTATION_LANDSCAPE:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                break;
            case Configuration.ORIENTATION_PORTRAIT:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
        switch (requestCode) {
            case FILE_CHOOSER_RESULT_CODE:
                if (null == myChromeClient.getmUploadMessage()) {
                    return;
                }
                myChromeClient.getmUploadMessage().onReceiveValue(result);
                myChromeClient.setmUploadMessage(null);
                break;
            case FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5:
                if (null == myChromeClient.getmUploadMessageForAndroid5())
                    return;
                if (result != null) {
                    myChromeClient.getmUploadMessageForAndroid5().onReceiveValue(new Uri[]{result});
                } else {
                    myChromeClient.getmUploadMessageForAndroid5().onReceiveValue(new Uri[]{});
                }
                myChromeClient.setmUploadMessageForAndroid5(null);
                break;
//            case PictureConfig.CHOOSE_REQUEST:
//                if (resultCode == RESULT_OK) {
//                    List<LocalMedia> localMedias = PictureSelector.obtainMultipleResult(intent);
//                    if (localMedias.size() == 1) {
//                        String compressPath = localMedias.get(0).getCompressPath();
//                        upLoadImage(compressPath);
//                    } else {
//                        upLoadMultiImage(localMedias);
//                    }
//                }
//                break;
            case 100:
                if (resultCode == RESULT_OK) {
                    String compressPath = intent.getAction();
//                    upLoadImage(compressPath);
                }
                break;

        }
    }


    @Override
    public void loadFinished(String title, boolean isError) {
    }



    /*--------------------------------H5 调用原生--------------------------------*/

    private static class JsInterfaceHandler extends Handler {
        private WeakReference<Activity> weakRefActivity;
        private WebViewActivity context;
        private WebView webViews;
        private RelativeLayout contentLayout;
        public JsInterfaceHandler(WebViewActivity activity, WebView webViews, RelativeLayout contentLayout) {
            this.context = activity;
            weakRefActivity = new WeakReference<>(activity);
            this.webViews = webViews;
            this.contentLayout = contentLayout;
        }

        @Override
        public void handleMessage(Message msg) {
            Activity activity = weakRefActivity.get();
            if (activity != null) {
                switch (msg.what) {
                    case BACK:
                        activity.finish();
                        break;
                    case GOTOCAPTURE:
                        captureWebView1(context, webViews);
                        break;
                    case GOTOMAIN:
                        Intent intent3 = new Intent(context, MainActivity.class);
                        context.startActivity(intent3);
                        context.finish();
                        break;
                    case DOWNLOAD:
                        String dl_s = (String) msg.obj;
                        downloadImage(context, dl_s);
                        break;
                    case SAVE:
                        String sa_s = (String) msg.obj;
                        QrMessageBean qrMessageBean = GsonUtils.jsonToBean(sa_s, QrMessageBean.class);
                        Log.e("message", qrMessageBean.toString());
                        captureWebView2(context, webViews, contentLayout, qrMessageBean);
                        break;

                }
            }
        }

    }

    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        //进度显示
        if (newProgress > 80) {
            prograssBar.setVisibility(View.GONE);
        } else {
            prograssBar.setProgress(newProgress);
        }
    }

    @Override
    public void onReceivedTitle(WebView view, String title) {
        //网页加载完成 这里设置标题
        if (title.contains("http") || title.contains("网页无法打开") || title.contains(".com") || title.contains(".cn")) {
            return;
        }
    }



    /**
     * 对WebView进行截图
     *
     * @param webView
     * @return
     */
    public static void captureWebView1(Context context, WebView webView) {//可执行
        PermissionHelper.getInstance().getPermission((FragmentActivity) context, new PermissionHelper.PermissionCallBack() {
            @Override
            public void onSuccess() {
                Bitmap viewBitmap = SaveViewToImageUtil.getViewBitmap(webView);
                String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + context.getString(R.string.app_name);
                String fileName = System.currentTimeMillis() + ".jpg";
                boolean b = ImageUtil.saveImageToGallery(context, viewBitmap, storePath, fileName);
                if (b) {
                    Toast.makeText(context, "截图保存成功，请在相册查看", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFail() {
                Toast.makeText(context, "获取权限失败", Toast.LENGTH_SHORT).show();
            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }




    public static void downloadImage(Context context, String imageUrl) {//可执行

        PermissionHelper.getInstance().getPermission((FragmentActivity) context, new PermissionHelper.PermissionCallBack() {
            @Override
            public void onSuccess() {
                Glide.with(context)
                        .asBitmap()
                        .load(imageUrl)
                        .into(new CustomTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {

                                String storePath = context.getFilesDir().getAbsolutePath() + File.separator + "截图";
                                String fileName = System.currentTimeMillis() + ".png";
                                boolean b = ImageUtil.saveImageToGallery(context, resource, storePath, fileName);
                                if (b) {
                                    Toast.makeText(context, "保存成功，请在相册查看", Toast.LENGTH_SHORT).show();

                                } else {
                                    Toast.makeText(context, "保存失败，请重试", Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onLoadCleared(@Nullable Drawable placeholder) {
                                Toast.makeText(context, "保存失败，请重试", Toast.LENGTH_SHORT).show();
                            }
                        });
            }

            @Override
            public void onFail() {
                Toast.makeText(context, "获取权限失败", Toast.LENGTH_SHORT).show();
            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }


    /**
     * 3.0通用下载图片
     *
     * @param contentView
     * @return
     */
    public static void captureWebView2(Context context, WebView webView, RelativeLayout contentView, QrMessageBean messageBean) {
        PermissionHelper.getInstance().getPermission((FragmentActivity) context, new PermissionHelper.PermissionCallBack() {
            @Override
            public void onSuccess() {
                Glide.with(context)
                        .asBitmap()
                        .load(messageBean.getAdvCode())
                        .into(new CustomTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                if (messageBean.getIsAdditional().equals("1")) {  // 需要加载信息数据
                                    contentView.setVisibility(View.VISIBLE);
                                    TextView memberName = contentView.findViewById(R.id.tv_message_title);

                                    String name = messageBean.getMemberName();
                                    if (name.length() > 10) {
                                        name = name.substring(0, 10) + "\n" + name.substring(10);
                                    }
                                    memberName.setText(name);
                                    TextView textss = contentView.findViewById(R.id.tv_message_text);
                                    textss.setText(messageBean.getText());
                                    TextView tip = contentView.findViewById(R.id.tv_message_tips);
                                    tip.setText(messageBean.getTip());
                                    ImageView qrView = contentView.findViewById(R.id.iv_message_qr);
                                    Glide.with(context)
                                            .load(messageBean.getQrcodeUrl())
                                            .into(new CustomTarget<Drawable>() {
                                                @Override
                                                public void onResourceReady(@NonNull Drawable drawableResource, @Nullable Transition<? super Drawable> transition) {
                                                    qrView.setImageDrawable(drawableResource);
                                                    String storePath = context.getFilesDir().getAbsolutePath() + File.separator + "截图";
                                                    String fileName = System.currentTimeMillis() + ".png";
                                                    Bitmap viewBitmap = SaveViewToImageUtil.getViewBitmap(contentView);
                                                    float widthScale = (float) resource.getWidth() / (float) viewBitmap.getWidth();
                                                    Matrix matrix = new Matrix();
                                                    matrix.postScale(widthScale, widthScale);  //长和宽放大缩小的比例
                                                    Bitmap resizeBmp = Bitmap.createBitmap(viewBitmap, 0, 0, viewBitmap.getWidth(),
                                                            viewBitmap.getHeight(), matrix, true);
                                                    Bitmap ImageBitmap = Bitmap.createBitmap(resource.getWidth(), resource.getHeight() + resizeBmp.getHeight(),
                                                            resource.getConfig());
                                                    Canvas canvas = new Canvas(ImageBitmap);
                                                    canvas.drawBitmap(resource, new Matrix(), null);
                                                    canvas.drawBitmap(resizeBmp, 0, resource.getHeight(), null);
                                                    boolean b = ImageUtil.saveImageToGallery(context, ImageBitmap, storePath, fileName);
                                                    if (b) {
                                                        Toast.makeText(context, "保存成功，请在相册查看", Toast.LENGTH_SHORT).show();
                                                        webView.loadUrl("javascript:" + messageBean.getSuccess() + "()");
                                                        //获取剪贴板管理器
                                                        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                                                        // 创建普通字符型ClipData
                                                        ClipData mClipData = ClipData.newPlainText("Label", messageBean.getCopyText());
                                                        // 将ClipData内容放到系统剪贴板里。
                                                        cm.setPrimaryClip(mClipData);
                                                    } else {
                                                        Toast.makeText(context, "保存失败，请重试", Toast.LENGTH_SHORT).show();
                                                        webView.loadUrl("javascript:" + messageBean.getFail() + "()");
                                                    }
                                                }

                                                @Override
                                                public void onLoadCleared(@Nullable Drawable placeholder) {
                                                    Toast.makeText(context, "保存失败，请重试", Toast.LENGTH_SHORT).show();
                                                    webView.loadUrl("javascript:" + messageBean.getFail() + "()");
                                                }
                                            });
                                } else {
                                    String storePath = context.getFilesDir().getAbsolutePath() + File.separator + "截图";
                                    String fileName = System.currentTimeMillis() + ".png";
                                    boolean b = ImageUtil.saveImageToGallery(context, resource, storePath, fileName);
                                    if (b) {
                                        Toast.makeText(context, "保存成功，请在相册查看", Toast.LENGTH_SHORT).show();
                                        webView.loadUrl("javascript:" + messageBean.getSuccess() + "()");
                                        //获取剪贴板管理器
                                        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                                        // 创建普通字符型ClipData
                                        ClipData mClipData = ClipData.newPlainText("Label", messageBean.getCopyText());
                                        // 将ClipData内容放到系统剪贴板里。
                                        cm.setPrimaryClip(mClipData);
                                    } else {
                                        Toast.makeText(context, "保存失败，请重试", Toast.LENGTH_SHORT).show();
                                        webView.loadUrl("javascript:" + messageBean.getFail() + "()");
                                    }
                                }


                            }

                            @Override
                            public void onLoadCleared(@Nullable Drawable placeholder) {
                                Toast.makeText(context, "保存失败，请重试", Toast.LENGTH_SHORT).show();
                                webView.loadUrl("javascript:" + messageBean.getFail() + "()");
                            }
                        });
            }

            @Override
            public void onFail() {
                Toast.makeText(context, "获取权限失败", Toast.LENGTH_SHORT).show();
            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }




}
